package com.org.utils.io;

import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;

import com.org.utils.date.DateUtils;


public class ImageUploadServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	//上传根目录
	private String rootPath ="";
	//上传图片目录
	private String imgPath="resource/attach/treecard/pic/";
	//上传临时目录
	private String tempPath="temp";
	//水印文字
	private String watermarkText="www.dress.com";
	
	
	
	private long defaultMaxUploadSize = (1024 * 1024) * 1024;
//	private BuyerUser currentBuyer;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		try
		{
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=utf-8");
			defaultMaxUploadSize = request.getParameter("maxSize") != null ? Long.valueOf(request.getParameter("maxSize")) : defaultMaxUploadSize;
			rootPath = getServletContext().getRealPath("/");
			//currentBuyer = (BuyerUser) request.getSession().getAttribute(GlobalConstant.CURRENT_SESSION_USER);
			
			if(""==null)
			{
				JSONObject rs = new JSONObject();
				rs.put("remoteUrl", "");
				rs.put("message", "上传失败!");
				response.getWriter().write(rs.toString());
				return;
			}
			
			if (request.getParameter("method") != null && request.getParameter("method").trim().equals("uploadImage"))
			{
				uploadImage(request, response);
			}
		} catch (Exception e)
		{
			response.getWriter().write(e.getMessage());
			e.printStackTrace();
		}
	}

	private void uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception
	{

		String savePath = request.getParameter("savePath");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		/**
		 * 想要上传大于100M不抛异常的重要的一个设置setSizeThreshold 这个方法是用于设置存储到TEMP文件夹的临界值；
		 * 意思是当大于这个值的时候文件将存于临时文件夹中而不存在内存而导致内存溢出 越小越好 ken-2009
		 */
		factory.setSizeThreshold(1024 * 1024 * 1);
		File tempFile = new File(rootPath+imgPath +tempPath );
		if ((!(tempFile.exists())) && (!(tempFile.isDirectory())))
		{
			tempFile.mkdir();
		}
		factory.setRepository(tempFile);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(defaultMaxUploadSize);
		upload.setSizeMax(defaultMaxUploadSize);

		List<?> items = upload.parseRequest(request);
		for (int i = 0; i < items.size(); ++i)
		{
			FileItem fileItem = (FileItem) items.get(i);
			if (!(fileItem.isFormField()))
			{
				if ((fileItem.getName() == null) || (fileItem.getSize() <= 0L))
				{
					continue;
				}
				// 取出文件扩展名
				String extension = fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
				// 创建一个唯一的ID以防止重名被覆盖
				String UUName = UUID.randomUUID().toString();
				// 判断从页面传过来的参数是否是需要从服务器获取的配置路径
				if (this.isSaveWithConfig(savePath))
				{
					savePath = this.getSavePath(savePath, fileItem, UUName);
				}
				// 检查要保存文件的路径是否已存在，如果未存在则创建路径
				String directoryStr = rootPath+imgPath + savePath;
				File directory = new File(directoryStr);
				if ((!(directory.exists())) && (!(directory.isDirectory())))
				{
					directory.mkdirs();
				}
				// 写出文件
				File file = new File(directory, UUName + extension);
				fileItem.write(file);
				fileItem.delete();

				// 创建三种等比例缩放尺寸的图片 大图800×600/中图400×300/小图180×135
				ImageHandler.scale((directoryStr + UUName + extension), (directoryStr + "b_" + UUName + extension), 800, 600);// 大图800×600
				ImageHandler.scale((directoryStr + UUName + extension), (directoryStr + "m_" + UUName + extension), 400, 300);// 中图400×300
				//ImageHandler.scale((directoryStr + UUName + extension), (directoryStr + "s_" + UUName + extension), 180, 135);// 小图180×135
				// 添加水印,小图不添加
				ImageHandler.textMark((directoryStr + UUName + extension), watermarkText, new Font("宋体", Font.BOLD, 35), Color.white, 0, 0, 0.8F);
				ImageHandler.textMark((directoryStr + "b_" + UUName + extension), watermarkText, new Font("宋体", Font.BOLD, 35), Color.white, 0, 0, 0.8F);
				ImageHandler.textMark((directoryStr + "m_" + UUName + extension), watermarkText, new Font("宋体", Font.BOLD, 35), Color.white, 0, 0, 0.8F);

				JSONObject rs = new JSONObject();
				rs.put("remoteUrl", imgPath+savePath + UUName + extension);
				rs.put("message", "上传成功!");
				response.getWriter().write(rs.toString());

			}
		}

	}

	public String getSavePath(String key, FileItem fileItem, String UUName)
	{

		StringBuffer sb = new StringBuffer();
		
		
		// 树牌图片上传
		if (key.trim().equals("{uploadTreeCardImage}"))
		{
//			sb.append("upload/");
//			sb.append(currentBuyer.getLoginName() + "/");
//			sb.append(UUName + "/");
			//sb.append(currentBuyer.getLoginName());
			sb.append("/");
			sb.append(DateUtils.formatDate(new Date(), "yyyyMMdd"));
			sb.append("/");
		}

		return sb.toString();
	}

	public Boolean isSaveWithConfig(String key)
	{
		return key.startsWith("{") && key.endsWith("}");
	}

}
